package com.lqw.wechat.app.controller;

import com.lqw.wechat.common.util.WeChatUtil;
import com.lqw.wechat.service.wechatservice.WeChatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created by luqiwen on 2017/6/16.
 */
@Controller
@RequestMapping("/weChat")
public class WeChatController {

    private static final Logger logger= LoggerFactory.getLogger(WeChatUtil.class);

    @Autowired
    private WeChatService weChatService;

    /**
     *  校验微信 token
     * @param request
     * @param response
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/process",method = RequestMethod.GET)
    public String process(HttpServletRequest request, HttpServletResponse response,
                                 @RequestParam() String signature,
                                 @RequestParam() String timestamp,
                                 @RequestParam() String nonce,
                                 @RequestParam() String echostr){
        logger.info("微信服务器校验参数 : signature:{} , timestamp:{} , nonce:{} , echostr:{}", new Object[]{signature, timestamp, nonce, echostr});
        return WeChatUtil.checkToken(signature, timestamp, nonce)==Boolean.FALSE?null:echostr;
    }

    /**
     *  微信入口处理
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/process",method = RequestMethod.POST)
    public String process(HttpServletRequest request, HttpServletResponse response){
        try {
            Map<String, String> paramMap = WeChatUtil.xml2Map(request.getInputStream());
            return weChatService.process(paramMap);
        }catch (Exception e){
            logger.error("微信入口处理异常",e);
        }
        return null;
    }

}
